package com.test.mylotterysystem.comment.utils;


import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.json.JsonParseException;
import org.springframework.util.ReflectionUtils;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    // 作为工具类不需要创建实例对象
    private JacksonUtil() {
    }

    ;

    private static final ObjectMapper objectMapper;

    static {
        objectMapper = new ObjectMapper();
    }

    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    public static final <T> T tryParse(Callable<T> parser) {
        return JacksonUtil.tryParse(parser, JacksonException.class);
    }

    // 用于不用繁琐的抛出异常并进行处理
    public static final <T> T tryParse(Callable<T> parser, Class<? extends Exception> check) {
        try {
            return parser.call();
        } catch (Exception var4) {
            if (check.isAssignableFrom(var4.getClass())) {
                throw new JsonParseException(var4);
            } else {
                ReflectionUtils.rethrowRuntimeException(var4);
                throw new IllegalStateException(var4);
            }
        }
    }

    /**
     * 封装Jackson中常见的方法
     */

    public static String writeValueAsString(Object object) {
        return JacksonUtil.tryParse(() -> {
            return objectMapper.writeValueAsString(object);
        });
    }

    public static <T> T readValue(String str, Class<T> type) {
        return tryParse(() -> {
            return objectMapper.readValue(str, type);
        });
    }

    public static <T> T readListValue(String str, Class<?> valueType) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, valueType);
        return tryParse(() -> {
            return objectMapper.readValue(str, javaType);
        });
    }


}
